package com.maxlen.coupon.interceptor;

import com.maxlen.common.constant.LoginConstant;
import com.maxlen.common.utils.JwtUtils;
import com.maxlen.common.utils.R;
import com.maxlen.common.utils.ResponseUtils;
import com.maxlen.common.utils.ResultCode;
import com.maxlen.coupon.entity.to.LoginInfoTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static ThreadLocal<LoginInfoTO> threadLocalID = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean match = new AntPathMatcher().match("/coupon/reception/**", request.getRequestURI());
        if(match){
            String header = request.getHeader(LoginConstant.TOKEN);
            if(StringUtils.hasText(header)){
                if(JwtUtils.checkToken(header)){
                    String id = JwtUtils.getMemberIdByJwtToken(header);
                    if(StringUtils.hasText(id)){
                        String s = stringRedisTemplate.opsForValue().get(LoginConstant.MEMBER_LOGIN + id);
                        if(StringUtils.hasText(s)){
                            LoginInfoTO loginInfoTO = new LoginInfoTO();
                            loginInfoTO.setMemberId(Long.valueOf(id));
                            loginInfoTO.setMemberName(JwtUtils.getMemberAccountByJwtToken(header));
                            threadLocalID.set(loginInfoTO);

                            return true;
                        }else{
                            ResponseUtils.out(response, R.error(ResultCode.USER_ACCOUNT_EXPIRED));
                            return false;
                        }
                    }
                }
            }
        } else {
            return true;
        }
        ResponseUtils.out(response, R.error(ResultCode.USER_NOT_LOGIN));
        return false;
    }
}
